package com.jlastu.androidsx.ui;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;


public class ChatActivity extends AppCompatActivity {

    TextView mTvName;
    TextView mTvAdd;
    RecyclerView mRecycleview;
    TextView mTvSend;
    EditText mEtContent;
    private PlanAdapter mPlanAdapter;
    private User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        user = (User) getIntent().getSerializableExtra("data");
        initView();
        initData();
        initEvent();
    }
    public void initView() {
        mTvName = findViewById(R.id.tv_name);
        mRecycleview = findViewById(R.id.recycleview);
        mTvSend = findViewById(R.id.tv_send);
        mEtContent = findViewById(R.id.et_content);
        mPlanAdapter = new PlanAdapter(this);
        mRecycleview.setAdapter(mPlanAdapter);
        mRecycleview.setLayoutManager(new LinearLayoutManager(this));
        mTvName.setText(getIntent().getStringExtra("data"));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    public void initData() {

        List<XiaoXiBean> response = null;
        try {
            response = App.dbManager.findAll(XiaoXiBean.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
        List<XiaoXiBean> datas = new ArrayList<>();
        if (response != null && response.size() > 0) {
            for (int i = 0; i < response.size(); i++) {
                if ((response.get(i).getMyname().equals(App.getInstance().user.getUser_id())
                        && response.get(i).getHaoyouname().equals(user.getUser_id()))
                        || (response.get(i).getMyname().equals(user.getUser_id() )
                        && response.get(i).getHaoyouname().equals(App.getInstance().user.getUser_id()))) {
                    datas.add(response.get(i));
                }
            }
            if (mPlanAdapter.getItemCount() == datas.size()) {

            } else {
                mPlanAdapter.setData(datas);
                mRecycleview.scrollToPosition(datas.size() - 1);
            }
        }

    }

    public void initEvent() {


        mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = mEtContent.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(ChatActivity.this, "请输入聊天内容", Toast.LENGTH_SHORT).show();
                    return;
                }

                String shijian = DateUtils.getTime();
                XiaoXiBean xiaoXiBean = new XiaoXiBean();
                xiaoXiBean.setId(System.currentTimeMillis() + "");
                xiaoXiBean.setContent(content);
                xiaoXiBean.setMyname(App.getInstance().user.getUser_id());
                xiaoXiBean.setHaoyouname(user.getUser_id());
                xiaoXiBean.setTime(shijian);
                try {
                    App.dbManager.save(xiaoXiBean);
                    Toast.makeText(ChatActivity.this, "发送成功",
                            Toast.LENGTH_SHORT).show();
                } catch (DbException e) {
                    e.printStackTrace();
                }
                mEtContent.setText("");
                initData();
            }
        });
    }

    public int ITEM_TYPE_LEFT = 1;
    public int ITEM_TYPE_RIGHT = 2;


    public class PlanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private Context context;
        private List<XiaoXiBean> dataBeans = new ArrayList<>();

        public PlanAdapter(Context context) {
            this.context = context;
        }

        public void setData(List list) {
            dataBeans = list;
            notifyDataSetChanged();
        }

        @Override
        public int getItemViewType(int position) {
            if (App.getInstance().user.getUser_id().equals(dataBeans.get(position).getMyname())) {
                return ITEM_TYPE_RIGHT;
            } else {
                return ITEM_TYPE_LEFT;
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == ITEM_TYPE_RIGHT) {
                View view = LayoutInflater.from(context).inflate(R.layout.item_right, parent, false);
                return new RightViewHolder(view);
            } else {
                View view = LayoutInflater.from(context).inflate(R.layout.item_left, parent, false);
                return new LeftViewHolder(view);
            }
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof RightViewHolder) {
                ((RightViewHolder) holder).chat_item_content_text.setText(dataBeans.get(position).getContent());
                ((RightViewHolder) holder).tv_time.setText(dataBeans.get(position).getTime());
                String path = UserDBUtils.getInstance(getApplicationContext()).getHeadUrlBy(App.getInstance().user.getUser_id());
                if (!TextUtils.isEmpty(path)){
                    Glide.with(ChatActivity.this).load(path).into(((RightViewHolder) holder).head);
                }

            } else {
                String path = UserDBUtils.getInstance(getApplicationContext()).getHeadUrlBy(user.getUser_id());
                if (!TextUtils.isEmpty(path)){
                    Glide.with(ChatActivity.this).load(path).into(((RightViewHolder) holder).head);
                }
                ((LeftViewHolder) holder).chat_item_content_text.setText(dataBeans.get(position).getContent());
                ((LeftViewHolder) holder).tv_time.setText(dataBeans.get(position).getTime());
            }
        }

        public void removeList(int position) {
            dataBeans.remove(position);//删除数据源,移除集合中当前下标的数据
            notifyItemRemoved(position);//刷新被删除的地方
            notifyItemRangeChanged(position, getItemCount()); //刷新被删除数据，以及其后面的数据
        }

        @Override
        public int getItemCount() {
            if (dataBeans != null && dataBeans.size() > 0) {
                return dataBeans.size();
            } else {
                return 0;
            }
        }

        class RightViewHolder extends RecyclerView.ViewHolder {
            private TextView chat_item_content_text;
            private TextView tv_time;
            CircleImageView head;

            public RightViewHolder(View itemView) {
                super(itemView);
                chat_item_content_text = itemView.findViewById(R.id.chat_item_content_text);
                tv_time = itemView.findViewById(R.id.tv_time);
                head = itemView.findViewById(R.id.head);
            }
        }

        class LeftViewHolder extends RecyclerView.ViewHolder {
            private TextView chat_item_content_text;
            private TextView tv_time;
            CircleImageView head;

            public LeftViewHolder(View itemView) {
                super(itemView);
                chat_item_content_text = itemView.findViewById(R.id.chat_item_content_text);
                head = itemView.findViewById(R.id.head);
                tv_time = itemView.findViewById(R.id.tv_time);
            }

        }
    }

}
